package com.jn.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class StudentService extends Service {

   private List<Student> mStudentList;
   private RemoteCallbackList<IStudentChangeListener> mListeners;

   @Override
   public void onCreate() {
      super.onCreate();
      mStudentList = new ArrayList<>();
      mListeners = new RemoteCallbackList<>();
      Log.d("StudentService", "Service Created");
   }

   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return stub;
   }

   IStudentService.Stub stub = new IStudentService.Stub() {
      @Override
      public void addListener(IStudentChangeListener listener) throws RemoteException {
         if (listener != null) {
            mListeners.register(listener);
         }
      }

      @Override
      public void addStudent(Student student) throws RemoteException {
         mStudentList.add(student);
         notifyCountChanged(getStudentCount());
      }

      @Override
      public void deleteStudent(int id) throws RemoteException {
         for (int i = 0; i < mStudentList.size(); i++) {
            if (mStudentList.get(i).getNumber() == id) {
               mStudentList.remove(i);
               notifyCountChanged(getStudentCount());
               return;
            }
         }
      }

      @Override
      public List<Student> getStudentList() {
         return mStudentList;
      }

      @Override
      public int getStudentCount() {
         return mStudentList.size();
      }
   };

   public void notifyCountChanged(int count) {
      final int N = mListeners.beginBroadcast();
      for (int i = 0; i < N; i++) {
         try {
            mListeners.getBroadcastItem(i).onStudentCountChanged(count);
         } catch (RemoteException e) {
            Log.d("StudentService", "Error notifying listeners");
         }
      }
      mListeners.finishBroadcast();
   }
}
